package com.sl.plugin.step.selenium.newtab;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;

import java.util.Set;

/**
 *
 */
public class SeleniumNewTabComp extends AbstractProcessComp<WebDriver, WebDriver> implements ProcessCompService {


    public SeleniumNewTabComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }


    @Override
    public WebDriver input(WebDriver driver) {
        String url = meta.getStrAttr("openUrl");
        String operatorCode = meta.getStrAttr("operatorCode");
        String index = meta.getStrAttr("index");

        if (StrUtil.equals(operatorCode, "open")) {
            String time = "window.open(\"" + url + "\");";
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript(time);

            Set<String> handles = driver.getWindowHandles();
            driver.switchTo().window(CollUtil.get(handles, handles.size() - 1));
        } else if (StrUtil.equalsAnyIgnoreCase(operatorCode, "close", "change")) {
            Set<String> handles = driver.getWindowHandles();
            WebDriver window = null;
            if (NumberUtil.isNumber(index)) {
                window = driver.switchTo().window(CollUtil.get(handles, Integer.valueOf(index)));
            } else {
                if (StrUtil.equals(index, "last")) {
                    window = driver.switchTo().window(CollUtil.get(handles, handles.size() - 1));
                } else if (StrUtil.equals(index, "first")) {
                    window = driver.switchTo().window(CollUtil.get(handles, 0));
                } else {
                    window = driver.switchTo().window(index);
                }
                if (ObjectUtil.isNotNull(window)) {
                    if (StrUtil.equalsAnyIgnoreCase(operatorCode, "close")) {
                        window.close();
                    }
                }

            }
        }

        return driver;
    }

}
